<template>
  <div class="course-container">
    <!-- 课程标题与进度 -->
    <div
      v-if="!loading && courseInfo?.courseName"
      class="course-header"
    >
      <div class="course-title-container">
        <h2 class="text-3xl font-bold text-slate-800 dark:text-slate-100">
          课程名称:
          {{ courseInfo.courseName }}
        </h2>
      </div>

      <div class="progress-container">
        <div class="progress-bar">
          <div
            class="progress-fill"
            :style="{ width: `${progress}%` }"
          />
        </div>
      </div>
    </div>

    <!-- 章节列表 -->
    <div
      v-if="!loading && courseChapters.length > 0"
      class="chapters-list"
    >
      <div
        v-for="chapter in courseChapters"
        :key="chapter.chapterId"
        class="chapter-item"
      >
        <div class="chapter-header">
          <h3 class="chapter-title">
            <i
              v-if="chapter.completed"
              class="fa fa-check-circle text-emerald-500 mr-2"
            />
            <i
              v-else
              class="fa fa-circle-o text-gray-400 mr-2"
            />
            章节名称:
            {{ chapter.chapterName }}
          </h3>
          <div class="chapter-meta">
            <div class="chapter-date">
              <i class="fa fa-calendar mr-1 text-blue-500" />
              {{ formatDate(chapter.updateTime) }}
            </div>
            <span class="chapter-info">
              {{ chapter.materials.length }}个资源
            </span>
          </div>
        </div>

        <button
          class="toggle-materials"
          @click="toggleMaterials(chapter.chapterId)"
        >
          {{ chapter.showMaterials ? '收起资料' : '查看资料' }}
          <i
            class="fa transition-transform duration-300"
            :class="chapter.showMaterials ? 'fa-chevron-up' : 'fa-chevron-down'"
          />
        </button>

        <transition
          name="slide"
          mode="out-in"
        >
          <div
            v-show="chapter.showMaterials"
            class="materials-list"
          >
            <div
              v-for="material in chapter.materials"
              :key="material.materialId"
              class="material-item"
            >
              <div class="material-icon">
                <!-- 或使用文章图标 -->
                <i class="material-icons">material</i>
              </div>
              <div class="material-details">
                <span class="material-name">{{ material.materialName }}</span>
              </div>
              <a
                :href="material.downloadUrl"
                class="btn-download"
                target="_blank"
              >
                <i class="fa fa-download mr-1" />下载
              </a>
            </div>
          </div>
        </transition>
      </div>
    </div>

    <!-- 空状态提示 -->
    <div
      v-if="!loading && courseChapters.length === 0"
      class="empty-state"
    >
      <div class="empty-illustration">
        <div class="book-icon">
          <i class="fa fa-book-open text-4xl" />
        </div>
        <p class="empty-title">
          暂无章节资料
        </p>
      </div>
      <p class="empty-subtitle">
        当前课程暂时没有可用的学习资源，老师正在努力准备中！
      </p>
      <button
        class="btn-back"
        @click="$router.go(-1)"
      >
        <i class="fa fa-arrow-left mr-2" />返回上一页
      </button>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="loading-container"
    >
      <div class="spinner" />
      <p class="loading-text">
        <i class="fa fa-book mr-2" />正在加载课程内容，请稍候...
      </p>
    </div>

    <!-- 错误提示 -->
    <div
      v-if="error"
      class="error-container"
    >
      <div class="error-icon">
        <i class="fa fa-exclamation-triangle" />
      </div>
      <p class="error-text">
        {{ error }}
      </p>
      <button
        class="btn-try-again"
        @click="loadData"
      >
        重试
      </button>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import axios from 'axios';
import {useRoute} from 'vue-router';
import {useUserStore} from '@/stores/userStore';

// 使用 useRoute 获取路由参数
const route = useRoute();

// 获取用户信息
const userStore = useUserStore();
const userId = computed(() => userStore.user.userId);

// 从路由参数获取课程ID
const courseId = ref(route.params.courseId || '');
console.log('课程ID:', courseId.value);
console.log('用户ID:', userId.value);

const courseInfo = ref({});
const courseChapters = ref([]);
const loading = ref(true);
const error = ref('');

// 计算进度
const progress = computed(() => {
  if (courseChapters.value.length === 0) return 0;
  const completed = courseChapters.value.filter(c => c.completed).length;
  return ((completed / courseChapters.value.length) * 100).toFixed(0);
});

// 切换资料展开状态
const toggleMaterials = (chapterId) => {
  courseChapters.value = courseChapters.value.map(chapter =>
      chapter.chapterId === chapterId
          ? {...chapter, showMaterials: !chapter.showMaterials}
          : chapter
  );
};

// 文件类型图标映射
const getFileIcon = (type) => {
  return {
    pdf: 'fa-file-pdf-o text-red-500',
    doc: 'fa-file-word-o text-blue-500',
    docx: 'fa-file-word-o text-blue-500',
    xls: 'fa-file-excel-o text-green-500',
    xlsx: 'fa-file-excel-o text-green-500',
    ppt: 'fa-file-powerpoint-o text-orange-500',
    pptx: 'fa-file-powerpoint-o text-orange-500',
    video: 'fa-file-video-o text-red-600',
    audio: 'fa-file-audio-o text-blue-600',
    image: 'fa-file-image-o text-indigo-500',
    zip: 'fa-file-archive-o text-gray-500',
    default: 'fa-file-o text-gray-500'
  }[type] || 'fa-file-o text-gray-500';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const options = {year: 'numeric', month: '2-digit', day: '2-digit'};
  return new Date(dateString).toLocaleDateString('zh-CN', options);
};

// 数据加载函数
const loadData = async () => {
  try {
    loading.value = true;
    error.value = '';

    // 1. 获取课程基本信息
    const courseResponse = await axios.get(`/api/courses/${courseId.value}`);
    courseInfo.value = courseResponse.data || {};

    // 2. 获取课程所有章节
    const chaptersResponse = await axios.get(`/api/chapters/course/${courseId.value}`);
    const allChapters = chaptersResponse.data || [];

    // 3. 获取学生已完成的章节ID列表
    const learnedChaptersResponse = await axios.get(
        `/api/chapters/student/${userId.value}/course/${courseId.value}/learned`
    );
    const learnedChapterIds = (learnedChaptersResponse.data || []).map(chapter => chapter.chapterId);

    // 4. 合并章节数据（添加完成状态和资料列表）
    courseChapters.value = await Promise.all(
        allChapters.map(async chapter => {
          try {
            // 获取章节下的所有资料
            const materialsResponse = await axios.get(
                `/api/materials/${courseId.value}/chapter/${chapter.chapterId}`
            );

            return {
              ...chapter,
              completed: learnedChapterIds.includes(chapter.chapterId),
              showMaterials: false,
              materials: (materialsResponse.data || []).map(material => ({
                ...material,
                type: material.materialName.split('.').pop() || 'default',
                downloadUrl: `/api/materials/${material.materialId}/download`
              }))
            };
          } catch (err) {
            console.error(`获取章节 ${chapter.chapterId} 资料失败:`, err);
            return {
              ...chapter,
              completed: learnedChapterIds.includes(chapter.chapterId),
              showMaterials: false,
              materials: []
            };
          }
        })
    );
  } catch (err) {
    console.error('数据加载失败:', err);
    error.value = '数据加载失败，请检查网络连接或重试';
    courseInfo.value = {};
    courseChapters.value = [];
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.course-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1.5rem;
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.course-header {
  margin-bottom: 3rem;
  padding: 2rem;
  background: linear-gradient(135deg, #f9fafe 0%, #eef5ff 100%);
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  border: 1px solid #e1e8ff;
}

.course-title-container {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
  gap: 1rem;
  flex-wrap: wrap;
}

.course-title-container h2 {
  font-size: 1.75rem;
  color: #1f2937;
}

.badge {
  background-color: #e0e7ff;
  color: #4f46e5;
  font-size: 0.85rem;
  padding: 0.3rem 0.8rem;
  border-radius: 20px;
  display: inline-flex;
  align-items: center;
  font-weight: 500;
}

.course-description {
  color: #4b5563;
  line-height: 1.7;
  margin-bottom: 2rem;
  background: #ffffff;
  padding: 1.2rem;
  border-radius: 10px;
  border-left: 4px solid #4f46e5;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03);
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  padding: 1.2rem;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.progress-bar {
  flex: 1;
  height: 10px;
  background-color: #e5e7eb;
  border-radius: 5px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(to right, #4f46e5, #7c3aed);
  border-radius: 5px;
  transition: width 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
}

.progress-percentage {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-percentage span {
  font-size: 1.5rem;
  font-weight: bold;
  color: #4f46e5;
}

.progress-percentage div {
  font-size: 0.85rem;
  color: #6b7280;
}

.chapters-list {
  display: flex;
  flex-direction: column;
  gap: 1.8rem;
}

.chapter-item {
  background: white;
  border-radius: 14px;
  padding: 1.8rem;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  transition: transform 0.25s ease, box-shadow 0.25s ease;
}

.chapter-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
  border-color: #e0e7ff;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.2rem;
  flex-wrap: wrap;
}

.chapter-title {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.chapter-meta {
  display: flex;
  gap: 1.2rem;
  font-size: 0.9rem;
  color: #64748b;
}

.chapter-date {
  display: flex;
  align-items: center;
}

.chapter-info {
  background: #f5f7ff;
  padding: 0.2rem 0.8rem;
  border-radius: 20px;
  color: #4f46e5;
  font-weight: 500;
}

.toggle-materials {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-top: 1.2rem;
  padding: 0.7rem;
  background-color: #f8fafc;
  color: #4f46e5;
  border: 1px dashed #dbeafe;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.toggle-materials:hover {
  background-color: #e0e7ff;
  border-style: solid;
}

.materials-list {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid #f1f5f9;
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.material-item {
  display: flex;
  align-items: center;
  padding: 0.9rem 1.2rem;
  background: #f8fafc;
  border-radius: 12px;
  transition: all 0.2s ease;
}

.material-item:hover {
  background: #eff6ff;
  transform: translateX(5px);
}

.material-icon {
  width: 42px;
  height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  background: #e0e7ff;
  margin-right: 1rem;
  font-size: 1.25rem;
}

.material-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.material-name {
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 0.2rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.material-meta {
  font-size: 0.85rem;
  color: #64748b;
}

.btn-download {
  padding: 0.5rem 1.2rem;
  background-color: white;
  color: #4f46e5;
  border: 1px solid #e0e7ff;
  border-radius: 8px;
  font-weight: 500;
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
}

.btn-download:hover {
  background-color: #4f46e5;
  color: white;
}

/* 动画效果 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
  overflow: hidden;
}

.slide-enter-from {
  transform: scaleY(0.8);
  opacity: 0;
  max-height: 0;
}

.slide-enter-to {
  transform: scaleY(1);
  opacity: 1;
  /* 设置足够大的最大值，确保包含实际内容 */
  max-height: 2000px;
}

.slide-leave-active {
  max-height: 2000px;
  /* 为离开动画使用更快的效果 */
  transition: all 0.3s cubic-bezier(0.55, 0.085, 0.68, 0.53);
}

.slide-leave-to {
  transform: scaleY(0.8);
  opacity: 0;
  max-height: 0;
}

/* 资料列表 - 添加以下提升性能的属性 */
.materials-list {
  /* 确保浏览器不会在动画期间重新布局 */
  will-change: transform, opacity, max-height;
  /* 固定transform的原点 */
  transform-origin: top center;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 16px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
  margin-top: 2rem;
}

.empty-illustration {
  margin-bottom: 1.8rem;
}

.book-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #eef2ff;
  margin-bottom: 1.5rem;
  color: #6366f1;
  font-size: 2.5rem;
}

.empty-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.empty-subtitle {
  color: #64748b;
  max-width: 500px;
  margin: 0 auto 2rem;
  line-height: 1.7;
}

.btn-back {
  padding: 0.8rem 2rem;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  color: white;
  border: none;
  border-radius: 50px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
  transition: all 0.3s ease;
}

.btn-back:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

/* 加载状态 */
.loading-container {
  text-align: center;
  padding: 4rem;
}

.spinner {
  width: 60px;
  height: 60px;
  border: 5px solid #e0e7ff;
  border-top: 5px solid #4f46e5;
  border-radius: 50%;
  margin: 0 auto 2rem;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: #64748b;
  font-size: 1.1rem;
}

/* 错误状态 */
.error-container {
  text-align: center;
  padding: 3rem;
  background: #fff5f5;
  border-radius: 16px;
  border: 1px solid #fecaca;
}

.error-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #fee2e2;
  color: #ef4444;
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
}

.error-text {
  color: #b91c1c;
  margin-bottom: 2rem;
  font-size: 1.1rem;
}

.btn-try-again {
  padding: 0.8rem 2rem;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-try-again:hover {
  background: #dc2626;
  transform: scale(1.05);
}

/* 响应式 */
@media (max-width: 640px) {
  .course-container {
    padding: 0 1rem;
  }

  .course-header {
    padding: 1.5rem;
  }

  .progress-container {
    flex-direction: column;
    gap: 1rem;
  }

  .chapter-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
